<template>
  <view class="repairChart">
    <view class="roleBox">
      <view class="roleCard">{{ navTitle + "-统计" }}</view>
      <view class="changeBtn" @click="changePart">
        <image src="@/static/images/index/change.svg" mode=""></image>
        <view class="">切换</view>
      </view>
    </view>
    <!-- 执行任务star -->
    <view class="card">
      <view class="card-title">
        <view> 维修任务-执行数据</view>

        <view class="date-type" @click="clickDateBtn(d1)">
          {{
            d1.filter.dateType !== 4
            ? ["", "今天", "近7天", "近30天"][`${d1.filter.dateType}`]
            : `${d1.filter.startTime.replace(
              /-/g,
              "/"
            )}-${d1.filter.endTime.replace(/-/g, "/")}`
          }}
          <uni-icons size="20rpx" type="forward" style="line-height: 57rpx; margin-left: 2rpx" color="#999"></uni-icons>
        </view>
      </view>
      <view class="" v-if="d1.chartData.series.length">
        <view class="charts">
          <l-echart class="ring" ref="d1"></l-echart>
          <view class="data-lable">
            <view class="data-lable-item" v-for="(item, index) in d1.chartData.series" :key="index"
              @click="selectLegend(item, 'd1')" :style="{ color: colorMap[index] }">
              <view class="color" :style="{ background: item.show ? d1.colors[index] : '#ccc' }">
              </view>
              <view class="name">{{ item.name }}</view>
              <view class="num">{{ item.eleTotal }}单</view>
              <view class="eleTotal">{{ item.data }}%</view>
            </view>
          </view>
        </view>
        <view class="detail" @click="toDetail(1, d1)">
          详情
          <text class="next"></text>
        </view>
      </view>
      <view class="chartEmpty" v-else>
        <image src="@/static/images/index/empty1.png" mode=""></image>
        <view class="">暂无数据</view>
      </view>
    </view>
    <!-- 执行任务end -->
    <!-- 电梯故障统计 -->
    <view class="card">
      <view class="card-title">
        <view> 电梯维修统计 </view>
        <view class="date-type" @click="clickDateBtn(d2)">
          {{
            d2.filter.dateType !== 4
            ? ["", "今天", "近7天", "近30天"][`${d2.filter.dateType}`]
            : `${d2.filter.startTime.replace(
              /-/g,
              "/"
            )}-${d2.filter.endTime.replace(/-/g, "/")}`
          }}
          <uni-icons size="20rpx" type="forward" style="line-height: 57rpx; margin-left: 2rpx" color="#999"></uni-icons>
        </view>
      </view>
      <view class="" v-if="d2.chartData.series.length">
        <view class="charts">
          <l-echart class="ring" ref="d2"></l-echart>
          <view class="data-lable">
            <view class="data-lable-item" v-for="(item, index) in d2.chartData.series" :key="index"
              @click="selectLegend(item, 'd2')" :style="{ color: colorMap[index] }">
              <view class="color" :style="{ background: item.show ? d2.colors[index] : '#ccc' }">
              </view>
              <view class="name">{{ item.name }}</view>
              <view class="num">{{ item.eleTotal }}台</view>
              <view class="eleTotal">{{ item.data }}%</view>
            </view>
          </view>
        </view>
        <view class="detail" @click="toDetail(2, d2)">
          详情
          <text class="next"></text>
        </view>
      </view>
      <view class="chartEmpty" v-else>
        <image src="@/static/images/index/empty1.png" mode=""></image>
        <view class="">暂无数据</view>
      </view>
    </view>
  </view>
</template>

<script>
import * as echarts from '@/subpages/components/lime-echart/static/echarts.min';
import LEchart from '@/subpages/components/lime-echart/components/l-echart/l-echart.vue';
import { ringOptShowTitle } from '../utils/chart_opt.js';
import { getRepairStatus, getRepairRepetition } from '@/apis/statistic.js';
import { getBeforeDate, formatTime } from '@/utils/utils.js';
export default {
	components: { LEchart },
	props: {
		pageScrollTop: {
			type: [Number, String],
			default: 0,
		},
		safeAreaBottom: {
			type: [Number, String],
			default: 0,
		},
	},
	data() {
		return {
			navTitle: '',
			deptIds: [],
			getBeforeDate: getBeforeDate,
			formatTime: formatTime,
			d1: {
				// 执行数据
				colors: ['#ff89a8', '#fbcb92', '#98e8bc'],
				chartData: { series: [] },
				opts: {},
				showTitle: true,
				title: '',
				subtitle: '',
				chart: null,
				id: 'id' + new Date().getTime() + 'repairTask',
				filter: {
					dateType: 2, // 日期范围 1今天，2近七天，3近30天，4自定义日期
					startTime: getBeforeDate(7),
					endTime: formatTime(new Date().getTime() - 60 * 60 * 24 * 1000),
					applyToAll: false,
					name: 'repairTask',
				},
			},
			d2: {
				// 电梯故障
				colors: ['#ff89a8', '#fbcb92', '#98e8bc'],
				chartData: { series: [] },
				opts: {},
				title: '',
				subtitle: '',
				showTitle: true,
				chart: null,
				id: 'id' + new Date().getTime() + 'repairFalut',
				filter: {
					dateType: 3, // 日期范围 1今天，2近七天，3近30天，4自定义日期
					startTime: getBeforeDate(30),
					endTime: formatTime(new Date().getTime() - 60 * 60 * 24 * 1000),
					applyToAll: false,
					name: 'repairFalut',
				},
			},
			colorMap: {
				0: '#E02020',
				1: '#F79700',
				2: '#666666',
			},
		};
	},
	created() {
		uni.$on(this.d1.id, this.timeSubmit);
		uni.$on(this.d2.id, this.timeSubmit);
		// uni.getStorage({
		//   key: "repairStatistical",
		//   success: (res) => {
		//     console.log("修改数据源-维修", res);
		//     if (res.data.isFirst) {
		//       this.navTitle = res.data.title[0];
		//     } else {
		//       this.navTitle =
		//         res.data.title.length == 1
		//           ? res.data.title[0]
		//           : `已选${res.data.title.length}部门`;
		//     }

		//     this.deptIds = res.data.id;
		//     this.fetchStatus()
		//     this.fetchrRepetition()
		//   },
		// });
	},
	beforeDestroy() {
		uni.$off(this.d1.id);
		uni.$off(this.d2.id);

		console.log('[repair] beforeDestroy');
		uni.$off('setDatas');
	},
	async mounted() {
		this.$nextTick().then(() => {
			setTimeout(() => {
				console.log('[partSelect] on listen setDatas');
				uni.$on('setDatas', this.setDataFuc);
			}, 500);
		});
		this.setDataFuc();
	},
	methods: {
		setDataFuc() {
			console.log('[partSelect] setDataFuc setDataFuc维修页面');
			uni.getStorage({
				key: 'repairStatistical',
				success: (res) => {
					console.log('[partSelect] 修改数据源-维修统计', res);
					if (res.data.isFirst || res.data.id.length == 0) {
						this.navTitle = res.data.allGroupTitles[0] + '整体';
					} else {
						this.navTitle =
              res.data.id.length == 1
              	? res.data.title[0]
              	: `已选${res.data.id.length}部门`;
					}
					if (!res.data.id.length) {
						this.deptIds = res.data.allGroupIds;
					} else {
						this.deptIds = res.data.id;
					}

					this.fetchStatus();
					this.fetchrRepetition();
				},
			});
		},
		selectLegend(item, type) {
			console.log(item, 'item的至');
			let list = this[type].chartData.series;
			item.show = !item.show;

			let newList = list.filter((e) => e.show);
			if (!newList.length) {
				return;
			} else {
				this.setRingChart(type);
			}
		},
		setRingChart(chart, legend) {
			// 绘制环形图
			let color = this[chart].colors;
			let color2 = [];
			let list = this[chart].chartData.series;
			let chartData = [];
			let text = this[chart].showTitle ? this[chart].title : '';
			let subtext = this[chart].showTitle ? this[chart].subtitle : '';
			for (let i = 0; i < list.length; i++) {
				if (list[i].show) {
					chartData.push({
						value: list[i].data,
						name: list[i].name || '无',
					});
					color2.push(color[i]);
				}
			}
			console.log('setRingChart', chart, chartData, this[chart].chartData);
			this[chart].opts = ringOptShowTitle({
				color: color2,
				data: chartData,
				type: 'ring',
				showTitle: {
					text,
					subtext,
				},
			});
			this.$nextTick(() => {
				if (!this.$refs[chart]) {
					return;
				}
				this.$refs[chart].init(echarts, (chartF) => {
					// this.chartMaps[chart] = chartF
					chartF.setOption(this[chart].opts);
					// chartF.dispatchAction({
					//   type: "highlight",
					//   seriesIndex: 0,
					//   dataIndex: 0,
					// });
					chartF.on('mouseover', (e) => {
						console.log(e, 'e的值');
						chartF.setOption({
							title: {
								show: false,
							},
						});

						if (e.dataIndex !== 0) {
							// 当鼠标移除的时候 使默认的索引值去除默认选中
							chartF.dispatchAction({ type: 'downplay', dataIndex: 0 });
						}
					});
					chartF.on('mouseout', (e) => {
						chartF.setOption({
							title: {
								show: true,
							},
						});
					});
				});
			});
		},
		// 电梯任务
		fetchStatus() {
			const { startTime, endTime } = this.d1.filter;
			getRepairStatus({
				deptIds: this.deptIds,
				startDate: startTime,
				endDate: endTime,
			}).then((res) => {
				if (res) {
					console.log(res, '状态统计');
					let list = [];
					if (res.data.itemVOS != null) {
						for (let i = 0; i < res.data.itemVOS.length; i++) {
							list.push({
								name: res.data.itemVOS[i].label,
								eleTotal: res.data.itemVOS[i].num,
								data: res.data.itemVOS[i].per,
								show: true,
							});
						}
					}
					this.d1.chartData.series = list;
					// this.d1.title = res.data.planTotal;
					this.d1.title = list[0].data + '%';
					this.d1.subtitle = list[0].name;
					this.setRingChart('d1');
				}
			});
		},
		// 电梯故障明细
		fetchrRepetition() {
			const { startTime, endTime } = this.d2.filter;
			getRepairRepetition({
				deptIds: this.deptIds,
				startDate: startTime,
				endDate: endTime,
			}).then((res) => {
				if (res) {
					console.log(res, '重复故障统计');
					let list = [];
					if (res.data.itemVOS != null) {
						for (let i = 0; i < res.data.itemVOS.length; i++) {
							list.push({
								name: res.data.itemVOS[i].label,
								eleTotal: res.data.itemVOS[i].num, // 数量
								data: res.data.itemVOS[i].per, // 百分比
								show: true,
							});
						}
					}

					this.d2.chartData.series = list;
					console.log('list',list);
					// this.d2.title = res.data.elevatorTotal;
					this.d2.title = list[0].data + '%';
					this.d2.subtitle =  list[0].name;
					this.setRingChart('d2');
				}
			});
		},

		clickDateBtn(res) {
			console.log(res, '点击日期');
			uni.$emit('openTimeFilter', {
				id: res.id,
				safeAreaBottom: this.safeAreaBottom,
				...res.filter,
			});
		},
		timeSubmit(res) {
			// console.log("timeSubmit", res, 8888);
			// 如果应用到所有图表
			if (res.applyToAll) {
				this.d1.filter.dateType = res.dateType;
				this.d1.filter.startTime = res.startTime;
				this.d1.filter.endTime = res.endTime;
				this.d1.filter.name = 'repairTask';
				this.d2.filter.dateType = res.dateType;
				this.d2.filter.startTime = res.startTime;
				this.d2.filter.endTime = res.endTime;
				this.d2.filter.name = 'repairFalut';
				// console.log(this.d1,'d1',this.d2,'d2')
				// 统一请求
				this.fetchStatus();
				this.fetchrRepetition();
			} else {
				if (res.name == 'repairTask') {
					this.d1.filter = res;
					this.d1.filter.name = 'repairTask';
					this.fetchStatus();
				} else {
					this.d2.filter = res;
					this.d2.filter.name = 'repairFalut';
					// 分别请求
					this.fetchrRepetition();
				}
			}
		},
		toDetail(type, day) {
			const { dateType, startTime, endTime } = day.filter;
			uni.navigateTo({
				url: `/subpages/statistics/repair/detail?type=${type}&dateType=${dateType}&startTime=${startTime}&endTime=${endTime}`,
			});
		},
		changePart() {
			uni.navigateTo({
				url: '/subpages/statistics/partSelect',
			});
		},
	},
};
</script>

<style lang="scss"  scoped >
.repairChart {

  .roleBox {
    margin: 16rpx 20rpx;
    padding: 14rpx 20rpx 14rpx 0;
    background: #fff;
    border-radius: 8rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .roleCard {
      border-left: 4rpx solid #0091ff;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .changeBtn {
      color: #0091ff;
      font-size: 24rpx;
      display: flex;

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .date-type {
    color: #666666;
    font-size: 24rpx;
    height: 56rpx;
    padding-left: 10rpx;
    display: flex;
    align-items: center;
    border: 2rpx solid #d5d5d5;
    border-radius: 4rpx;
    text-align: center;
    justify-content: center;
    font-weight: normal;

    image {
      width: 20rpx;
      height: 20rpx;
      margin-left: 3rpx;
    }
  }

  .card {
    width: calc(100% - 40rpx);
    margin: 20rpx;
    background-color: #fff;
    border-radius: 8rpx;

    &-title {
      padding: 20rpx;
      color: #333333;
      font-size: 30rpx;
      font-weight: bold;
      letter-spacing: 1rpx;
      display: flex;
      justify-content: space-between;
    }

    .chartEmpty {
      height: 200rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #999;

      image {
        width: 64rpx;
        height: 64rpx;
      }
    }

    .charts {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      // position: relative;
      .chartsContent {

        // position: relative;
        .ringTitle {
          width: 200rpx;
          height: 200rpx;
          border-radius: 50%;
          position: absolute;
          top: 80rpx;
          left: 80rpx;
          background: #fff;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      }

      .ring {
        width: 320rpx;
        height: 320rpx;
        padding: 20rpx;
        padding-bottom: 40rpx;
        text-align: center;
        display: flex;
        align-items: center;
        font-size: 30rpx;
        color: #999;
        justify-content: center;
        // background-color: #ccc;
      }

      .pie {
        width: 100%;
        height: 440rpx;
        padding: 10rpx 0;
        text-align: center;
        display: flex;
        align-items: center;
        font-size: 30rpx;
        color: #999;
        justify-content: center;
      }

      .charts-box {
        width: 320rpx;
        height: 320rpx;
        padding: 20rpx;
        padding-bottom: 40rpx;
        position: relative;

        .ring {
          width: 320rpx;
          height: 320rpx;
          padding: 0rpx;
          padding-bottom: 0rpx;
          // background-color: #ccc;
          text-align: center;
          display: flex;
          align-items: center;
          font-size: 30rpx;
          color: #999;
          justify-content: center;
        }

        .init-pie {
          width: 320rpx;
          height: 320rpx;
          padding: 0rpx;
          padding-bottom: 0rpx;
          position: absolute;
          z-index: 1;
          top: 20rpx;
          left: 20rpx;
          text-align: center;
          display: flex;
          align-items: center;
          font-size: 30rpx;
          color: #999;
          justify-content: center;
        }
      }

      .data-lable {
        width: calc(100% - 380rpx);
        padding-right: 20rpx;

        &-info {
          width: 100%;
          display: flex;
          align-items: center;

          &-item {
            flex: 1;
            text-align: center;
            font-size: 26rpx;
            color: #999999;
            line-height: 42rpx;

            .num {
              font-size: 34rpx;
              font-weight: bold;
              color: #333;

              text {
                font-size: 30rpx;
              }
            }

            .red {
              color: #c01414;
            }

            .name {
              width: 100%;
              display: flex;
              align-items: center;
              text-align: center;
              justify-content: center;

              .color {
                // background-color: #0091FF;
                width: 16rpx;
                height: 16rpx;
                border-radius: 50%;
                margin-right: 12rpx;
              }

              .text {
                text-align: center;
                flex: 1;
              }
            }
          }

          &-item:nth-child(1) {
            padding-right: 16rpx;
            flex: none;
          }

          .line {
            width: 2rpx;
            height: 60rpx;
            background-color: #eeeeee;
          }
        }

        &-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 26rpx;
          margin: 16rpx 0;
          color: #666666;

          .color {
            // background-color: #0091FF;
            width: 16rpx;
            height: 16rpx;
            border-radius: 50%;
            margin-right: 12rpx;
          }

          .name {
            width: calc(100% - 160rpx - 28rpx);
            overflow: hidden;
            text-overflow: ellipsis; //文本溢出显示省略号
            white-space: nowrap; //文本不会换行
          }

          .eleTotal {
            width: 70rpx;
            text-align: center;
            text-align: right;
          }

          .num {
            width: 90rpx;
            text-align: center;
            text-align: right;
          }
        }
      }
    }

    .detail {
      color: #0091ff;

      display: flex;
      align-items: center;

      justify-content: flex-end;
      align-items: center;
      padding: 0 30rpx 32rpx 0;

      .next {
        display: inline-block;
        width: 12rpx;
        height: 12rpx;
        margin-left: 10rpx;
        border-left: 3rpx #0091ff solid;
        border-top: 3rpx #0091ff solid;
        transform: rotate(135deg);
      }
    }
  }
}
</style>
